#include "couriersys.h"
#include "ui_couriersys.h"

CourierSYS::CourierSYS(QString username, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CourierSYS)
{
    ui->setupUi(this);
    client = new Client();
    this->username = username;
    modelInit();
    connect(ui->workBtn, &QPushButton::clicked, this, &CourierSYS::taskReceived);

}

CourierSYS::~CourierSYS()
{
    delete ui;
}

void CourierSYS::modelInit()
{
    model = new QSqlTableModel(this);
    model->setTable("expressinfo");
    model->setHeaderData(0, Qt::Horizontal, "订单号");
    model->setHeaderData(1, Qt::Horizontal, "物品类型");
    model->setHeaderData(2, Qt::Horizontal, "寄件人");
    model->setHeaderData(3, Qt::Horizontal, "寄件时间");
    model->setHeaderData(4, Qt::Horizontal, "收件人");
    model->setHeaderData(5, Qt::Horizontal, "快递员");
    model->setHeaderData(6, Qt::Horizontal, "物流状态");
    model->setHeaderData(7, Qt::Horizontal, "收件时间");
    model->setHeaderData(8, Qt::Horizontal, "价格");


    model->setFilter(QString("courier = '%1'").arg(username));
    ui->tableView->setModel(model);
    model->select();
    showBalance();
}

void CourierSYS::taskReceived()
{
    int row = ui->tableView->currentIndex().row();

    // 错误处理
    QString status = model->index(row, 6).data().toString();
    if (status == "已签收" || status == "待签收") {
        QMessageBox::warning(this, "错误", "非法操作！");
        return;
    }
    QString id = model->index(row, 0).data().toString();
    double price = model->index(row, 8).data().toDouble();
//    QSqlQuery query;
//    query.exec(QString("UPDATE expressinfo set status = '待签收' WHERE id = '%1'").arg(id));
    client->sendMsg(QString("UPDATE expressinfo set status = '待签收' WHERE id = '%1'").arg(id));
    QTimer::singleShot(1000, [=](){
        client->sendMsg(QString("快递员 %1 揽收快递#").arg(username));
        model->select();
    });

    // 转钱
    qDebug() << "快递员挣钱";
    Courier *courier = new Courier(this->username);
    courier->charge(price * 0.5);
    Admin *admin = new Admin("admin");
    admin->charge(price * (-0.5));
    model->select();
    showBalance();
}

void CourierSYS::showBalance()
{
    QSqlQuery query;
    query.exec(QString("SELECT * FROM userinfo WHERE username = '%1'").arg(username));
    if (query.next()) {
        ui->balanceEdit->setText(query.value(3).toString());
    }
}
